package com.example.dishit.view.alert;

import java.util.concurrent.atomic.AtomicInteger;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.example.dishit.R;
import com.example.dishit.model.dish.DishData;
import com.example.dishit.view.main.MainActivity;
import com.example.dishit.view.recommendation.RecommendationActivity;

public class AlertView {
    private static boolean enabled = false;
    private static AtomicInteger numUnopened = new AtomicInteger(0);
    
    public static final String RESET_NUM_UNOPENED_KEY = "resetNumUnopened";
    
    
    /**
     * Draw an alert.
     * 
     * @param tickerMsg the ticker text to be displayed
     * @param title the title in the notification shade to be displayed
     * @param context the current context
     * @param dishes the Dishes to send out alerts for
     */
    public static void drawAlert(final Context context, final String tickerMsg, final DishData dish) {
        if(!enabled) return;
        
        // Display a Status Notification.
        final Notification.Builder builder = new Notification.Builder(context)
                                                .setContentTitle(numUnopened.incrementAndGet() + " New Dishes!")
                                                .setSmallIcon(R.drawable.ic_launcher)
                                                .setTicker(tickerMsg)
                                                .setAutoCancel(true)
                                                .setContentIntent(createIntent(context, dish));
        final NotificationManager nm  = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        nm.notify(1, builder.build());
        
        // Display a Toast.
        Toast.makeText(context, tickerMsg, Toast.LENGTH_LONG).show();
    }
    
    public static void resetCounter() {
        numUnopened.set(0);
    }
    
    public static void setEnabled(final boolean enabled) { AlertView.enabled = enabled; }
    
    private static PendingIntent createIntent(final Context context, final DishData restaurant) {
        final Intent[] intents = new Intent[2];
        intents[0] = new Intent(context,  MainActivity.class);
        
        intents[1] = new Intent(context,  RecommendationActivity.class);
        intents[1].putExtra(DishData.DISH_DATA_KEY, restaurant);
        intents[1].putExtra(RESET_NUM_UNOPENED_KEY, true);
        
        return PendingIntent.getActivities(context, 0, intents, PendingIntent.FLAG_CANCEL_CURRENT);
    }
}
